<template>
  <page-header-wrapper>
    <template v-slot:content>
      <div class="page-header-content">
        <div class="avatar">
          <a-avatar size="large" :src="studentInfo.avater"/>
        </div>
        <div class="content">
          <div class="content-title">
            {{ studentInfo.name }}<span class="welcome-text"></span>
          </div>
          <div> {{ studentInfo.phone }} | {{ studentInfo.school }}</div>
        </div>
      </div>
    </template>
    <a-card :bordered="false">
      <!-- 操作 -->
      <div class="table-operations">
        <a-button type="primary" @click="$refs.createForm.handleAdd(studentInfo,cardCount)" v-hasPermi="['manager:studentCard:modify']">
          <a-icon type="plus" />新增
        </a-button>
        
        <a-button type="primary" @click="giftOpen(studentInfo)"  v-hasPermi="['manager:studentCard:modify']">
          <a-icon type="plus" />赠卡
        </a-button>

        <a-button type="primary" @click="getDelayRecord"  v-hasPermi="['manager:studentCard:modify']">
          <a-icon type="search" />延期/停卡
        </a-button>
        
        <a-button type="primary" @click="toStudentPage"  v-hasPermi="['manager:studentCard:modify']">
          <a-icon type="rollback" />返回
        </a-button>
      </div>
      <!-- 手风琴 -->
      <a-tabs default-active-key="1">
        
        <template v-for="(item,index) in cardInfoList">
          <a-tab-pane :key="index + 1" :tab="item.tab">
            <div>
              <a-collapse accordion :bordered="false" >
                <template v-for="(info,sub) in item.cardInfo">
                  <a-collapse-panel :key="sub" :header="info.cardName">
                      <a-descriptions  :column="5" >
                        <a-descriptions-item label="会员卡名称">
                          {{info.cardStatusName}}
                          <template v-if="info.transferName != null ">
                             （转让人： {{info.transferName}}）
                          </template>
                        </a-descriptions-item>
                        <a-descriptions-item label="基础卡有效期">
                          {{info.period}}
                        </a-descriptions-item>
                        <a-descriptions-item :label="info.isGift == 'A' ? '业绩归属校区' : ''">
                          {{info.ascription}}
                        </a-descriptions-item>
                        <a-descriptions-item :label="info.isGift == 'A' ? '业绩归属人' : ''">
                          {{info.ascriptionSale}}
                        </a-descriptions-item>
                        <a-descriptions-item  >
                          <template v-if="info.status == 'A' || info.status == 'B'">
                            <a-button type="primary"  
                              style="width:150px"
                              v-hasPermi="['manager:studentCard:modify']"
                              @click="
                                if(info.isGift == 'B'){  
                                  giftForm.studentId = studentId;
                                  giftForm.studentCardId = info.id
                                  giftForm.deptId = deptId;
                                  giftForm.giftType = info.giftType;
                                  giftForm.count = info.remainCount;
                                  giftForm.remark = info.remark;
                                  giftForm.time = info.time;
                                  giftForm.timeType = info.timeType.toString();
                                  openGift = true;
                                }else{
                                  $refs.createForm.handleUpdate(info,studentId,deptId)
                                }
                              "
                            >
                              修改
                            </a-button>
                          </template>
                        </a-descriptions-item>
                        <a-descriptions-item label="基础卡课次">
                          <template v-if="info.count > 0">
                            {{info.count}}次
                          </template>
                        </a-descriptions-item>
                        <a-descriptions-item label="剩余基础卡课次">
                          <template v-if="info.count > 0">
                            {{info.remainCount}}次
                          </template>
                        </a-descriptions-item>
                        <a-descriptions-item :label="info.isGift == 'A' ? '收费方式' : ''">
                          {{info.chargeType}}
                        </a-descriptions-item>
                        <a-descriptions-item :label="info.isGift == 'A' ? '收费金额' : ''">
                          {{info.charge ? info.charge + '元' : ''}}
                        </a-descriptions-item>
                        <a-descriptions-item  >
                          <template  v-if="info.status == 'A'">
                            <a-button type="primary" style="width:150px"  v-hasPermi="['manager:studentCard:modify']"
                              @click="modalOpen = true;modalTitle='卡管理';modalFlag=1;cuttentCard=info;form={}">卡管理</a-button>
                          </template>
                        </a-descriptions-item>
                        <a-descriptions-item label="开卡日期">
                          {{info.open}}
                        </a-descriptions-item>
                        <a-descriptions-item label="有效期">
                          {{info.validateStart}}
                        </a-descriptions-item>
                        <a-descriptions-item :label="info.isGift == 'A' ? '收费时间' : ''">
                          {{info.chargeTime}}
                        </a-descriptions-item>
                        <a-descriptions-item :label="info.isGift == 'A' ? '协议编号' : ''">
                          {{info.agreement}}
                        </a-descriptions-item>
                        <a-descriptions-item >
                          <template  v-if="info.status == 'A' && currentDeptId == 100">
                            <a-button type="primary" style="width:150px"   v-hasPermi="['manager:studentCard:modify']"
                              @click="openRemoveCardWindow(info)">删除</a-button>
                          </template>
                        </a-descriptions-item>
                        <a-descriptions-item label="赠品">
                          {{info.give}}
                        </a-descriptions-item>
                        <a-descriptions-item label="备注">
                          {{info.remark}}
                        </a-descriptions-item>
                        <a-descriptions-item :label="info.isGift == 'A' ? '收据编号' : ''">
                          {{info.chargeNum}}
                        </a-descriptions-item>
                        <a-descriptions-item label="">
                        </a-descriptions-item>
                        <a-descriptions-item >
                          <!-- <a-button type="primary" style="width:150px" 
                              @click="modalOpen = true;modalTitle='修改业绩归属校区';modalFlag=3;cuttentCard=info">
                              修改业绩归属校区
                          </a-button> -->
                        </a-descriptions-item>
                        <template v-if="info.cardStatus === 'C'">
                          <a-descriptions-item label="停课时长">
                            {{info.stopTime}}天
                          </a-descriptions-item>
                          <a-descriptions-item label="停课原因">
                            {{info.stopReason}}
                          </a-descriptions-item>
                        </template>
                        
                      </a-descriptions>
                  </a-collapse-panel>
                </template>
              </a-collapse>
            </div>
          </a-tab-pane>
        </template>
      </a-tabs>
      <!-- 增加修改 -->
      <create-form
        ref="createForm"
        @ok="getList"
      />
    </a-card>

    <!-- 卡管理模态框 -->
    <a-modal v-model="modalOpen" width="50%" :title="modalTitle" @ok="modifyStudentCard" >
      <a-spin :spinning="spinning" size="large">
        <a-form-model ref="form" :label-col="{span:4}" :wrapper-col="{span:18}"  :model="form" >
          <a-form-model-item label="类型">
            <a-radio-group v-model="form.dealType" button-style="solid" @change="dealTypeChange">
              <a-radio-button :value="1" v-if="cuttentCard.cardStatus != 'A'">开卡</a-radio-button>
              <a-radio-button :value="2" v-if="cuttentCard.isGift != 'B'">停卡</a-radio-button>
              <a-radio-button :value="3" v-if="cuttentCard.isGift != 'B'">升卡</a-radio-button>
              <template v-if="currentDeptId == 100">
                <a-radio-button :value="4" v-if="cuttentCard.isGift != 'B'">转卡</a-radio-button>
                <a-radio-button :value="5" >退卡</a-radio-button>
                <a-radio-button :value="6" >暑假班升卡（已开卡）</a-radio-button>
              </template>
            </a-radio-group>
          </a-form-model-item>
          <template v-if="form.dealType == 1">
            <a-form-model-item label="开卡日期">
              <a-date-picker @change="timeChange" />
            </a-form-model-item>
            <a-form-model-item label="有效期" >
              {{timeChangeData}}
            </a-form-model-item>
          </template>
          <template v-if="form.dealType == 2">
            <a-form-model-item label="停卡次数">
              第{{form.stopCount}}次
            </a-form-model-item>
            <a-form-model-item label="有效期结束时间">
              {{cardEndTime}}
            </a-form-model-item>
            <a-form-model-item label="停卡日期">
              <a-date-picker @change="stopTimeChange" />
            </a-form-model-item>
            <!-- <a-form-model-item label="停卡时长（天）">
              <a-input v-model="stopTime" @blur.native="stopBlur"></a-input>
            </a-form-model-item> -->
            <a-form-model-item label="停卡原因">
              <a-input v-model="form.stopReason"></a-input>
            </a-form-model-item>
            <!-- <a-form-model-item label="开卡时间">
              {{openCard}}
            </a-form-model-item>
            <a-form-model-item label="停卡之后的有效期">
              {{cardValidate}}
            </a-form-model-item> -->
          </template>
          <a-form-model-item label="剩余金额" v-if="form.dealType == 3 || form.dealType == 4 || form.dealType == 5">
              {{form.remain != null ? form.remain + '元': ''}}
            </a-form-model-item>
          <template v-if="form.dealType == 3 || form.dealType == 6">
            
            <a-form-model-item label="选择会员卡" >
              <a-select placeholder="请选择会员卡" v-model="form.cardId" style="width: 100%" allow-clear @change="cardChange">
                <a-select-option v-for="(d, index) in cardList" :key="index" :value="d.id" v-if="d.cardType <= 2">{{ d.name }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="会员卡信息">
              <a-descriptions :column="1">
                <a-descriptions-item label="卡类型">
                  {{cardInfo.cardTypeName}}
                </a-descriptions-item>
                <a-descriptions-item label="总次数/总时长" v-if="cardInfo.flag">
                  {{cardInfo.count}}
                </a-descriptions-item>
                <a-descriptions-item label="有效期">
                  {{cardInfo.desc}}
                </a-descriptions-item>
              </a-descriptions>
            </a-form-model-item>
            <a-form-model-item label="实际金额" v-if="form.dealType != 3">
              <a-input v-model="form.chargeAmount"></a-input>
            </a-form-model-item>
            <a-form-model-item label="补费金额">
              <a-input v-model="form.supplement"></a-input>
            </a-form-model-item>
          </template>
          <template v-if="form.dealType == 4">
            <a-form-model-item label="转让人">
              <a-input v-model="form.transferName"  @click.native="openStudentModal"/>
            </a-form-model-item>
            <a-form-model-item label="转让人手机号">
              {{form.transferPhone}}
            </a-form-model-item>
          </template>
          <template v-if="form.dealType == 5">
            <a-form-item label="退费原因">
              <a-radio-group v-model="form.refundReason" button-style="solid" >
                <a-radio-button value="1" >操作失误</a-radio-button>
                <a-radio-button value="2">客户意向</a-radio-button>
              </a-radio-group>
            </a-form-item>
            <a-form-model-item label="退费金额">
              <a-input v-model="form.refund" />
            </a-form-model-item>
          </template>
        </a-form-model>
      </a-spin>
    </a-modal>

    <!-- 人员查找模态框 -->
    <a-modal v-model="studentOpen" width="80%" title="学员列表" @ok="choseStudent">
      <a-row>
         <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="学员名称" prop="name">
                <a-input v-model="queryParam.name" placeholder="请输入学员名称" allow-clear/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="手机号" prop="phone">
                <a-input v-model="queryParam.phone" placeholder="请输入手机号" allow-clear/>
              </a-form-item>
            </a-col>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <a-button type="primary" @click="getStudentList"><a-icon type="search" />查询</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <a-table
            :loading="loading"
            :size="tableSize"
            rowKey="id"
            :columns="columns"
            :data-source="list"
            :pagination="false"
            :bordered="tableBordered"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange,type: 'radio'}"
          />
        <a-pagination
            class="ant-table-pagination"
            :current="queryParam.pageNum"
            :total="total"
            :page-size="queryParam.pageSize"
            :showTotal="total => `共 ${total} 条`"
          />
      </a-row>
    </a-modal>

    <!-- 新增赠卡 -->
    <a-modal v-model="openGift" width="40%" title="赠卡" @ok="submitGift">
      <a-row>
        <div class="table-page-search-wrapper">
          <a-form layout="inline" >
            <a-form-item label="类型">
              <a-radio-group v-model="giftForm.giftType" button-style="solid" >
                <a-radio-button :value="1">次卡</a-radio-button>
                <a-radio-button :value="2">时间卡</a-radio-button>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="次数" v-if="giftForm.giftType == 1">
              <a-input v-model="giftForm.count" placeholder="请输入赠课次数" allow-clear/>
            </a-form-item>
            <a-form-item label="有效期" prop="time" style="margin-bottom: 50px;">
              <a-input v-model="giftForm.time" placeholder="请输入有效期" />
              <a-radio-group v-model="giftForm.timeType" button-style="solid">
                <a-radio-button v-for="(d, index) in timeTypeOptions" :key="index" :value="d.dictValue">{{ d.dictLabel }}</a-radio-button>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="备注" >
              <a-input v-model="giftForm.remark" placeholder="请输入备注" allow-clear/>
            </a-form-item>
          </a-form>
        </div>
      </a-row>
    </a-modal>

    <!-- 延期/停卡 -->
    <a-modal v-model="openDelay" width="80%" title="延期/停卡" @ok="openDelay=false">
      <a-row>
        <div class="table-page-search-wrapper">
          <a-table
            :loading="delayLoading"
            rowKey="id"
            :columns="delayColumns"
            :data-source="delayList"
            :pagination="false"
            :bordered="tableBordered"
          >
          <span slot="stop" slot-scope="text, record">
            {{ record.type == 'A' ? record.createTime : '' }}
          </span>
          <span slot="delay" slot-scope="text, record">
            {{ record.updateTime }}
          </span>
          <span slot="type" slot-scope="text, record">
            {{ record.type == 'A' ? '停卡' : (record.type == 'B' ? '延期' : '修改课次') }}
          </span>
          <span slot="day" slot-scope="text, record">
            {{ record.type == 'A' || record.type == 'B' ? record.day + '天' : record.count + '次' }}
          </span>
        </a-table>
        </div>
      </a-row>
    </a-modal>

    <!-- 删除卡 -->
    <a-modal v-model="remoteCardWindow" width="30%" title="删除卡片" @ok="handleRemoveCard">
      <div class="table-page-search-wrapper">
          <a-form layout="inline" >
            <a-form-model-item label="缴费日期">
              {{ remoteCardDate }}
            </a-form-model-item>
          </a-form>
        </div>
    </a-modal>

  </page-header-wrapper>
</template>

<script>
import { listStudentCard,updateStudentCard,saveGift,delayRecard,removeCard} from '@/api/manager/studentCard'
import { getStudent,getOwnerGroup,listStudent} from '@/api/manager/student'
import {treeselect} from '@/api/system/dept'
import { getCardList } from '@/api/manager/card'
import CreateForm from './modules/CreateForm'
import { tableMixin } from '@/store/table-mixin'
import { mapGetters } from 'vuex'
import { PageHeaderWrapper } from '@/components/ProLayout'
import moment from 'moment'
import storage from'store'


export default {
  name: 'StudentCard',
  components: {
    CreateForm,
    PageHeaderWrapper
  },
  mixins: [tableMixin],
  data () {
    return {
      removeCard:null,
      remoteCardDate:null,
      remoteCardMonth:null,
      remoteCardWindow: false,
      spinning:false,
      openDelay:false,
      giftTime:[],
      giftForm:{
        giftType: 1
      },
      openGift:false,
      cardInfo:{
        cardTypeName:null,
        count:null,
        desc:null,
        flag:true
      },
      cardList:[],
      stopTime:null,
      cardEndTime:null,
      openCard:null,
      cardValidate:null,
      timeChangeData:null,
      dataSource:[],
      treeData:[],
      value:'',
      form:{},
      modalTitle:null,
      cuttentCard:{},
      modalFlag: 0,
      modalOpen:false,
      cardInfoList:[],
      cardCount:0,
      studentInfo:{},
      studentId:0,
      actions: [
        { type: 'star-o', text: '156' },
        { type: 'like-o', text: '156' },
        { type: 'message', text: '2' },
      ],
      delayList:[],
      list: [],
      selectedRowKeys: [],
      deptId:null,
      currentDeptId:null,
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      loading: false,
      total: 0,
      // 查询参数
      queryParam: {
        name:null,
        status:'B',
        id:null,
        studentId: null,
        pageSize: 10
      },
      studentOpen:false,
      columns: [
        {
          title: '学员名称',
          dataIndex: 'name',
          ellipsis: true,
          fixed: 'left',
          align: 'center'
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          ellipsis: true,
          align: 'center'
        },
        {
          title: '归属校区',
          dataIndex: 'deptName',
          ellipsis: true,
          align: 'center'
        },
        {
          title: '服务销售',
          dataIndex: 'ascriptionSaleName',
          ellipsis: true,
          align: 'center'
        }
      ],
      delayColumns: [
        {
          title: '学员名称',
          dataIndex: 'name',
          ellipsis: true,
          fixed: 'left',
          align: 'center'
        },
        {
          title: '卡包',
          dataIndex: 'card',
          ellipsis: true,
          align: 'center'
        },
        {
          title: '类型',
          dataIndex: 'type',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'type' },
        },
        {
          title: '停卡时长',
          dataIndex: 'day',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'day' },
        },{
          title: '备注',
          dataIndex: 'remark',
          ellipsis: true,
          align: 'center'
        },{
          title: '停卡时间',
          dataIndex: 'createTime',
          ellipsis: true,
          scopedSlots: { customRender: 'stop' },
          align: 'center'
        },{
          title: '开卡时间',
          dataIndex: 'createTime',
          ellipsis: true,
          scopedSlots: { customRender: 'delay' },
          align: 'center'
        }
      ],
      selectOptions:[
        {key:1,value:1,name:'一月份'},
        {key:2,value:2,name:'二月份'},
        {key:3,value:3,name:'三月份'},
        {key:4,value:4,name:'四月份'},
        {key:5,value:5,name:'五月份'},
        {key:6,value:6,name:'六月份'},
        {key:7,value:7,name:'七月份'},
        {key:8,value:8,name:'八月份'},
        {key:9,value:9,name:'九月份'},
        {key:10,value:10,name:'十月份'},
        {key:11,value:11,name:'十一月份'},
        {key:12,value:12,name:'十二月份'},
      ],
      timeTypeOptions:[]
    }
  },
  filters: {
  },
  created () {
    this.remoteCardMonth = (moment().month() + 1) + "";
    this.queryParam.name = this.$route.query.name;
    this.studentId = this.$route.query.studentId;
    this.queryParam.id = this.studentId;
    this.deptId = this.$route.query.deptId;
    this.giftForm.deptId = this.deptId;
    this.getStudentInfo();
    this.getList();
    this.getOwner();
    this.getTreeSelect();
    this.cardSelect();
    this.getDicts('time_type').then(response => {
      this.timeTypeOptions = response.data
    })
    this.currentDeptId = storage.get("deptId");
  },
  computed: {
    ...mapGetters([
      'avatar',
      'nickname'
    ])
  },
  watch: {
  },
  methods: {
    openRemoveCardWindow(card){
      this.removeCard = card;
      this.remoteCardWindow = true;
      console.log(card)
      this.remoteCardDate = card.isGift == 'A' ? moment(card.chargeTime).format("YYYY-MM-DD") 
                  : '赠卡'
    },
    handleRemoveCard(){
      let that = this;
      let card = this.removeCard
      card.month = this.remoteCardMonth;
      if(this.remoteCardMonth == null || this.remoteCardMonth == ''){
        this.$message.error("请选择删卡月份！");
        return false;
      }
      this.$confirm({
        title: '确认删除所选中数据?',
        content: '确认删除该学员卡包？',
        onOk () {
          removeCard({id:card.id,month:card.month}).then(resp => {
            that.remoteCardWindow = false
            that.getList();
            that.$message.success('删除成功！');
          })
        },
        onCancel () {}
      })
    },
    getDelayRecord(){
      delayRecard({
        studentId: this.studentId
      }).then(resp => {
          this.delayList = resp
          this.openDelay = true
      });
    },
    updateCard(info,studentId,deptId){
      if(info.getType == 'B'){
        this.giftForm.studentId = studentId;
        this.giftForm.deptId = deptId;
        this.openGift = true;
      }else{
        $refs.createForm.handleUpdate(info,studentId,deptId)
      }
    },
    submitGift(){
      saveGift(this.giftForm).then(resp => {
        if(resp.code == 200){
          this.$message.success("新增赠卡成功！");
          this.getList();
          this.openGift = false;
        }else{
          this.$message.error(resp.msg);
        }
      });
    },
    giftOpen(student){
      this.giftForm.studentId = student.id;
      this.openGift = true;
    },
    giftTimeChange(value,dateString){
      this.giftForm.start = dateString[0];
      this.giftForm.end = dateString[1];
    },
    choseStudent(){
      this.form.transferName = this.selectedRows[0].name;
      this.form.transferId = this.selectedRows[0].id;
      this.form.transferPhone = this.selectedRows[0].phone;
      this.studentOpen = false;
    },
    openStudentModal(){
       this.studentOpen = true;
       this.getStudentList();   
    },
    getStudentList () {
      this.loading = true
      listStudent(this.queryParam).then(response => {
        this.list = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    cardChange(value,option){
      let data = this.cardList[option.key];
      this.cardInfo.cardTypeName = data.cardTypeName;
      this.cardInfo.count = data.count;
      this.cardInfo.desc = data.desc;
      if(data.time == null){
        this.cardInfo.flag = false;
      }else if(data.cardType == 2){
        this.cardInfo.flag = false;
      }else{
        this.cardInfo.flag = true;
      }
    },
    cardSelect(){
      getCardList().then(resp => {
        this.cardList = resp.data;
      });
    },
    stopBlur(){
        this.form.stopTime = this.stopTime;
        this.openCard = moment(this.form.stopDate).add(parseInt(this.form.stopTime),"days").format('YYYY-MM-DD');
        this.cardValidate = moment(this.cardEndTime).add(parseInt(this.form.stopTime),"days").format('YYYY-MM-DD');
        this.form.startTime = this.openCard
        this.form.endTime = this.cardValidate
    },
    dealTypeChange(){

      this.form.startTime = null;
      this.form.endTime = null;
      this.form.remain = null;

      // A 正常卡----转入卡
      //   A 已开卡、B 未开卡、C 停卡
      // B 失效卡(过期失效、次数用完失效)
      // C 退卡
      // D 转出卡
      if(this.form.dealType === 1){
        this.form.status = 'A';
        this.form.cardStatus = 'A';
      }else{
        if(!(this.cuttentCard.status == 'A' && this.cuttentCard.cardStatus == 'A') && this.form.dealType != 5 && this.form.dealType != 3){
          this.$message.error('未开卡用户，禁止操作！');
          this.form.dealType = 1;
          return;
        }
        if(this.form.dealType === 2){
          this.form.status = 'A';
          this.form.cardStatus = 'C';
          this.form.stopCount = this.cuttentCard.stopCount;
          this.form.endTime = moment(this.cuttentCard.endTime).format('YYYY-MM-DD');
          this.cardEndTime = this.form.endTime
          this.form.startTime = moment(this.cuttentCard.startTime).format('YYYY-MM-DD');
          this.form.stopTime = this.cuttentCard.stopTime;
        }else if(this.form.dealType === 3){
          this.form.remain = this.cuttentCard.remain;
          this.form.status = 'S'
          this.form.cardStatus = null
        }else if(this.form.dealType === 4){
          this.form.remain = this.cuttentCard.remain;
          this.form.status = 'D'
          this.form.cardStatus = null
        }else if(this.form.dealType === 5){
          this.form.remain = this.cuttentCard.remain;
          this.form.status = 'C'
          this.form.cardStatus = null
        }
      }
    },
    modifyStudentCard(){

      if(this.form.dealType == 1){
        if(this.form.startTime == null || this.form.endTime == null){
          this.$message.error('请选择开卡日期！')
          return false;
        } 
      }else if(this.form.dealType == 2){
        if(this.form.stopReason == null || this.form.stopReason == ''){
          this.$message.error('请填写停卡原因！')
          return false;
        }
        console.log(this.form.stopDate)
        if(this.form.stopDate == null){
          this.$message.error('请选择正确的停卡时间！')
          return false;
        }
      }else if(this.form.dealType == 3){
        if(this.form.cardId == null){
          this.$message.error('请选择卡种！')
          return ;
        } if(this.form.supplement == null){
          this.$message.error('请填写补费金额！')
          return false;
        } 
      }else if(this.form.dealType == 4){
        if(this.form.transferId == null){
          this.$message.error('请选择转让人！')
          return false;
        } 
      }else if(this.form.dealType == 5){      
        if(this.form.refundReason == null){
          this.$message.error("请填写退费原因！")
          return false;
        }
        if(this.form.refund == null || this.form.refund < 0){
          this.$message.error('退费金额填写有误！')
          return false;
        } 
        this.form.month = this.remoteCardMonth  
      }else if(this.form.dealType == 6){      
        if(this.form.cardId == null){
          this.$message.error('请选择卡种！')
          return ;
        } if(this.form.chargeAmount == null){
          this.$message.error('请填写实际金额！')
          return ;
        } if(this.form.supplement == null){
          this.$message.error('请填写补费金额！')
          return false;
        } 
      }

      this.spinning = true;
      this.form.id = this.cuttentCard.id;
      this.form.deptId = this.deptId;
      updateStudentCard(this.form).then(response => {
          this.$message.success(
            '修改成功',
            3
          )
          this.$emit('ok')
          this.getList();
          this.spinning = false
          this.modalOpen = false;
      })
    },
    getTreeSelect(){
      treeselect().then(resp => {
        this.treeData =resp.data;
      })
    },
    getOwner(){
      getOwnerGroup().then(resp => {
        this.dataSource = resp.data;
      });
    },
    stopTimeChange(value){
      // if(moment(value).format("YYYY-MM-DD") < moment(new Date()).format("YYYY-MM-DD")){
      //   this.$message.error('停卡卡时间不能大于当前时间！')
      //   this.form.startTime = null;
      //   this.form.endTime = null;
      //   return false;
      // }else 
      if(moment(value).format("YYYY-MM-DD") < moment(new Date()).format("YYYY-MM-DD")){
        this.$message.error('停卡卡时间不能小于当前时间！')
        this.form.startTime = null;
        this.form.endTime = null;
        return false;
      }
      
      this.form.stopDate = moment().format("YYYY-MM-DD"); ;
    },
    timeChange(value){
      if(moment(value) >= moment(new Date())){
        this.$message.error('开卡时间不能大于当前时间！')
        this.form.startTime = null;
        this.form.endTime = null;
        return;
      }

      //设置开卡日期
      this.form.open = moment(value).format('YYYY-MM-DD');
      //停卡
      if(this.cuttentCard.cardStatus == 'C'){
        //计算相差天数 
        var diff = moment(value).diff(moment(this.cuttentCard.stopDate),'days');
        this.form.startTime = moment(this.cuttentCard.startTime).format('YYYY-MM-DD');
        this.form.endTime = moment(this.cuttentCard.endTime).add(diff,'days').format('YYYY-MM-DD');
        this.timeChangeData = this.form.startTime + '至' + this.form.endTime;
      }else{
        if(this.cuttentCard.cardType == 3 || this.cuttentCard.cardName == '赠卡'){
          //私教卡 或者赠卡
          var days = this.cuttentCard.timeType == 1 ? this.cuttentCard.time * 365
                  : this.cuttentCard.timeType == 2 ? this.cuttentCard.time * 30
                  : this.cuttentCard.time;
          this.form.startTime = moment(value).format('YYYY-MM-DD');
          this.form.endTime = moment(value).add(days - 1,'days').format('YYYY-MM-DD');
          this.timeChangeData = this.form.startTime + '至' + this.form.endTime;
        }else{
          if(this.cuttentCard.cardType < 3){
            this.form.startTime = moment(value).format('YYYY-MM-DD');
            this.form.endTime = moment(value).add(this.cuttentCard.timeCount - 1,'days').format('YYYY-MM-DD');
            this.timeChangeData = this.form.startTime + '至' + this.form.endTime;
          }else{
            this.form.startTime = this.cuttentCard.start;
            this.form.endTime = this.cuttentCard.end;
            this.timeChangeData = this.form.startTime + '至' + this.form.endTime;
          }
        }
      }

      //升卡后重开卡
      if(this.cuttentCard.transferName != null){
        this.form.startTime = this.cuttentCard.start;
        this.form.endTime = this.cuttentCard.end;
        this.timeChangeData = this.form.startTime + '至' + this.form.endTime;
      }

      // if(this.cuttentCard.start && moment(moment(value).format('YYYY-MM-DD')) > moment(this.cuttentCard.start)){
      //   this.$message.error('开卡时间不能大于有效期开始时间！')
      //   this.form.startTime = null;
      //   this.form.endTime = null;
      //   return;
      // }

    },
    getStudentInfo(){
      getStudent(this.studentId).then(a => {
         this.studentInfo  = a.data;
      })
    },
    toStudentPage(){
      this.$router.push({path:'/business/student',query: {deptId:this.deptId,name:this.queryParam.name}})
    },
    /** 查询人员卡包信息列表 */
    getList () {
      this.loading = true
      listStudentCard({studentId:this.studentId}).then(response => {
        this.cardInfoList = response.data.cardInfoList
        this.cardCount = response.data.cardCount
      })
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParam = {
        studentId: undefined,
        cardId: undefined,
        cardNo: undefined,
        count: undefined,
        giveCount: undefined,
        startTime: undefined,
        endTime: undefined,
        give: undefined,
        ascription: undefined,
        ascriptionSale: undefined,
        chargeAmount: undefined,
        charge: undefined,
        chargeNum: undefined,
        agreement: undefined,
        status: undefined,
        type: undefined,
        pageNum: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    onShowSizeChange (current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    changeSize (current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.ids = this.selectedRows.map(item => item.id)
      this.single = selectedRowKeys.length !== 1
      this.multiple = !selectedRowKeys.length
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      var that = this
      const ids = row.id || this.ids
      this.$confirm({
        title: '确认删除所选中数据?',
        content: '当前选中编号为' + ids + '的数据',
        onOk () {
          return delStudentCard(ids)
            .then(() => {
              that.onSelectChange([], [])
              that.getList()
              that.$message.success(
                '删除成功',
                3
              )
          })
        },
        onCancel () {}
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      var that = this
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk () {
          that.download('manager/studentCard/export', {
            ...that.queryParam
          }, `studentCard_${new Date().getTime()}.xlsx`)
        },
        onCancel () {}
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import "../../index.less";
</style>
